package com.horizon.common.configuration;

import com.horizon.common.interceptor.TokenInterceptor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringBootConfiguration;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.annotation.Bean;
import org.springframework.core.env.Environment;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.config.annotation.InterceptorRegistration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

/**
 * Token鉴权配置
 *
 * @author wangfuwei
 * @version 2018-08-13
 */
@SpringBootConfiguration
public class TokenConfiguration implements WebMvcConfigurer {
    @Autowired
    private Environment environment;

    @Autowired
    CrosConfiguration.TokenProperties tokenProperties;

    @Autowired
    DruidConfiguration.DruidProperties druidProperties;

    /**
     * Druid后台管理配置参数
     */
    @ConditionalOnMissingBean(DruidConfiguration.DruidProperties.class)
    @Bean
    public DruidConfiguration.DruidProperties druidProperties() {
        return new DruidConfiguration().druidProperties();
    }

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        String staticPath = environment.getProperty("spring.mvc.static-path-pattern");
        InterceptorRegistration interceptorRegistration = registry.addInterceptor(new TokenInterceptor()).addPathPatterns("/**");
        interceptorRegistration.excludePathPatterns("/error");
        interceptorRegistration.excludePathPatterns(tokenProperties.getExclude());

        //忽略拦截Druid后台监控
        if (druidProperties.getUrlMappings().length > 0) {
            interceptorRegistration.excludePathPatterns(druidProperties.getUrlMappings());
        }

        //忽略拦截静态资源
        if (!StringUtils.isEmpty(staticPath) && !staticPath.equals("/**")) {
            interceptorRegistration.excludePathPatterns(staticPath);
        }
    }
}
